// @Description：用于系统本身的设置处理
package ctrsystem

import (
    "github.com/astaxie/beego"
    "fmt"
    "time"
    "cloud_worm/util/umodels/mysqldb"
    "cloud_worm/util/umodels/mysqldb/dbmanager"
    "cloud_worm/wormweb/controllers/ctrconfig"
    "strconv"
    "github.com/astaxie/beego/logs"
)

var LogLevel int

const LogLevelConfigName = "log_level"

func LogLevelLoad() error {
    conf := &dbmanager.WebConfig{Name: LogLevelConfigName}
    if err := conf.Read("name"); err == nil {
        level, err := strconv.Atoi(conf.Value)
        if err != nil || (level > beego.LevelDebug || level < beego.LevelEmergency) {
            return fmt.Errorf("读WolConfig(%s)错误: %s", LogLevelConfigName, "parse leve config error")
        } else {
            LogLevel = level
            beego.SetLevel(LogLevel)
        }
    } else {
        return fmt.Errorf("读WolConfig(%s)错误: %s", LogLevelConfigName, err.Error())
    }

    logs.Info(fmt.Sprintf("set %s=%v", LogLevelConfigName, LogLevel))

    return nil
}

func LogLevelCheck(value string) error {
    level, err := strconv.Atoi(value)
    if err != nil {
        return fmt.Errorf("input log level: %s", err.Error())
    }
    if level > beego.LevelDebug || level < beego.LevelEmergency {
        return fmt.Errorf("log level must 0~~7, and input: %s", value)
    }
    return nil
}

func init()  {
    ctrconfig.RegisterConfigLoad(LogLevelConfigName, LogLevelLoad)
    ctrconfig.RegisterConfigCheck(LogLevelConfigName, LogLevelCheck)

    // 尝试创建该列数据
    conf := &dbmanager.WebConfig{Name: LogLevelConfigName}
    if err := conf.Read("name"); err != nil {
        conf.Commit = "日志级别"
        conf.Type = dbmanager.IntValue
        conf.Value = fmt.Sprintf("%d", beego.LevelInformational)
        conf.Created = time.Now().Unix()
        conf.Updated = conf.Created
        conf.Status = mysqldb.StatusValid
        conf.Insert()
    }

    LogLevelLoad()
}